﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SX.GateWay.Extention
{
    public static class AppBuilderExtensions
    {     
        /// <summary>
        /// 注册服务到Consul
        /// </summary>
        /// <param name="app"></param>
        /// <param name="lifetime"></param>
        /// <param name="consulEntity"></param>
        /// <param name="serviceList"></param>
        /// <returns></returns>
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime,Appsettings appsettings)
        {
            //请求注册的 Consul 地址
            var consulClint = new ConsulClient(c => c.Address = new Uri($"http://{appsettings.Consul.IP}:{appsettings.Consul.Port}"));
            if (appsettings.ServiceList != null && appsettings.ServiceList.Any())
            {
                var list = new List<AgentServiceRegistration>();
                appsettings.ServiceList.ForEach(s =>
                {
                    var httpCheck = new AgentServiceCheck()
                    {
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10),//服务启动多久后注册
                        Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔，或者称为心跳间隔
                        HTTP = $"http://{s.IP}:{s.Port}{s.HealthCheckUrl}",//健康检查地址
                        Timeout = TimeSpan.FromSeconds(10)
                    };
                    var registration = new AgentServiceRegistration()
                    {
                        Checks = new[] { httpCheck },
                        ID = $"{s.Name}-{s.IP}:{s.Port}",
                        Name = s.Name,
                        Address = s.IP,
                        Port = s.Port,
                        //这里后续可能需要修改
                        Tags = new[] { $"urlperfix-/{s.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签，以便 Fabio 识别
                    };
                    list.Add(registration);
                });
                //服务注册
                lifetime.ApplicationStarted.Register(() =>
                {
                    list.ForEach(i => { consulClint.Agent.ServiceRegister(i).Wait(); });                   
                });
                lifetime.ApplicationStopping.Register(() =>
                {
                    list.ForEach(i => { consulClint.Agent.ServiceDeregister(i.ID).Wait(); });                                        
                });
            }
            return app;
        }
    }
}
